package leetcode.d_1_99;

// https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
// 找出字符串中第一个匹配项的下标
public class P28 {
    public int strStr(String haystack, String needle) {
        int n = haystack.length();
        int m = needle.length();
        for(int i=0; i+m<=n; i++) {
            boolean flag = true;
            for(int j=0; j<m; j++) {
                if (haystack.charAt(i+j) != needle.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;

    }

    public int strStr2(String haystack, String needle) {
        int len = needle.length();
        if (haystack.substring(0, len).equals(needle)) {
            return 0;
        }
        int len2 = haystack.length();
        for(int i=1; i<=len2-len; i++) {
            if (haystack.substring(i, i+len).equals(needle)) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        P28 test = new P28();
//        System.out.println(test.strStr("sadbutsad", "sad"));
        System.out.println(test.strStr("abc", "c"));
    }
}
